<template>
  <el-container>
    <el-main>
      <el-row>
        <el-col :span="24" class="grade-desc">
          <strong>教师列表</strong>
          <el-row class="margin">
            <el-col :span="24">
              关键字：<el-input v-model="q.keyword" placeholder="请输入学生姓名" class="input"></el-input>
              年级：<el-select v-model="q.grade" placeholder="请选择">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
              <el-button type="primary" size="small" class="button" @click="query">搜索</el-button>
              <el-button type="info" size="small" @click="">重置</el-button>
              <el-button type="primary" :loading="exportLoading" @click="handleExport">
                导出excel
              </el-button>
              <el-button type="primary" @click="addDialog">添加</el-button>

              <!-- 添加 修改-->
              <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
                <!-- 内容主体区 -->
                <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="70px">
                  <el-form-item label="姓名" prop="studentId">
                    <el-select v-model="addForm.studentId" placeholder="请选择">
                      <el-option v-for="item in students" :key="item.studentInfo.id"
                        :label="item.studentInfo.studentName" :value="item.studentInfo.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="班级" prop="classId">
                    <el-select v-model="addForm.classId" placeholder="请选择">
                      <el-option v-for="item in classes" :key="item.classinfo.id" :label="item.classinfo.className"
                        :value="item.classinfo.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="科目" prop="subjectId">
                    <el-select v-model="addForm.subjectId" placeholder="请选择">
                      <el-option v-for="item in course" :key="item.course.id" :label="item.course.courseName"
                        :value="item.course.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="学期" prop="semesterName">
                    <el-select v-model="addForm.semesterName" placeholder="请选择">
                      <el-option v-for="item in semestes" :key="item.semesterName" :label="item.semesterName"
                        :value="item.semesterName">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="成绩" prop="score">
                    <el-input v-model="addForm.score"></el-input>
                  </el-form-item>

                </el-form>
                <!-- 底部区域 -->
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="save('addForm')">确 定</el-button>
                </span>
              </el-dialog>
            </el-col>
          </el-row>
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange" border>
            <el-table-column type="selection"> </el-table-column>
            <el-table-column prop="studnetInfo.studentName" label="姓名"> </el-table-column>
            <el-table-column prop="classInfo.className" label="班级"> </el-table-column>
            <el-table-column prop="termInfo.termName" label="学期"> </el-table-column>
            <el-table-column prop="courseInfo.courseName" label="科目"> </el-table-column>
            <el-table-column prop="scoreInfo.score" label="成绩"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateDialog(row)">
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteAA(row.teacherInfo.id)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-row>
            <el-col :span="24">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page.sync="currentPage1" :page-sizes="[5, 10, 15, 20]" :page-size="100"
                layout="total, prev, pager, next,sizes" :total="tatal">
              </el-pagination>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import dayjs from 'dayjs';
import axios from 'axios'
import { exportExcel } from "@/utils/excle";
import store from '@/store';
import { getScore, addScore, updataScore, deleteScore } from '@/api/scoreApi'
import { getClass } from '@/api/classApi'
import { getCourse } from '@/api/courseApi'
import { getStudents } from '@/api/studentApi'

export default {
  inject: ["reload"],
  data() {
    return {
      exportLoading: false,
      dialogVisible: false,
      // 用户信息个人
      personalInfo: {},
      // 添加、修改用户
      addForm: {
        studentId: "",
        subjectId: "",
        score: "",
        semesterName: "",
        classId: "",
      },
      semestes: [
        { semesterName: "第一学期" },
        { semesterName: "第二学期" },
        { semesterName: "第三学期" },
        { semesterName: "第四学期" },
        { semesterName: "第五学期" },
        { semesterName: "第六学期" },
      ],
      // 添加、修改标题
      title: "",
      // 班级
      classes: [],
      // 科目
      course: [],
      // 学生
      students: [],
      q: {
        // 初始页
        pageIndex: 1,
        // 返回数据量
        pageSize: 10,
        // 搜索关键字
        keyword: "",
        // 年级
        grade: "",
      },

      // 表单规则
      addFormRules: {
        studentId: [
          { required: true, message: "请输入学生姓名", trigger: "blur" },
        ],
        subjectId: [
          { required: true, message: "请选择科目", trigger: "blur" },
        ],
        score: [
          { required: true, message: "请输入科目成绩", trigger: "blur" },
        ],
        semesterName: [
          { required: true, message: "请输入学期", trigger: "blur" },
        ],
        classId: [
          { required: true, message: "请输入班级", trigger: "blur" },
        ],
      },
      // 总数据条数
      tatal: 50,
      // 年级
      options: [
        {
          label: "一年级",
          value: "1",
        },
        {
          label: "二年级",
          value: "2",
        },
        {
          label: "三年级",
          value: "3",
        },
        {
          label: "四年级",
          value: "4",
        },
      ],
      // 初始页为1
      currentPage1: 1,
      // 老师数据表
      tableData: [],
    };
  },
  created() {
    this.fetchData(1, 5, "")
    // 获取班级
    getClass().then(res => {
      this.classes = res.data.data
      // console.log(this.classes);
    })

    // 获取科目
    getCourse().then(res => {
      // console.log(res);
      this.course = res.data.data
    })
    // 获取学生
    getStudents(1, 100, "").then(res => {
      // console.log(res);
      this.students = res.data.data
    })
  },
  methods: {
    // 添加按钮
    addDialog() {
      this.addForm = {}
      this.title = '添加'
      this.dialogVisible = true
    },
    handleClose() { },
    // 添加、修改教师
    save(addForm) {
      this.$confirm('确定添加?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.$refs[addForm].validate((valid) => {
          if (valid) {
            if (this.title == '添加') {
              console.log(this.addForm);
              addScore(this.addForm).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                  this.$message.success(res.msg)
                  this.dialogVisible = false
                  this.reload()
                }
              })
            } else {
              console.log(this.addForm);
              this.addForm.id = this.personalInfo.scoreInfo.id
              console.log(this.personalInfo);
              updataScore(this.addForm.id, this.addForm).then(res => {
                // console.log(res);
                if (res.data.code == 200) {
                  this.$message.success(res.data.msg)
                  this.dialogVisible = false
                  this.reload();
                }
              })
            }

          } else {
            this.$message({
              showClose: true,
              message: "输入错误，请确认重试",
              type: "error",
            });
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },

    handleExport() {
      const header = [
        "入职时间",
        "姓名",
        "所在学院",
        "性别",
        "手机号",
        "住址",
      ];
      var list = []
      // console.log(this.tableData);
      for (let i = 0; i < this.tableData.length; i++) {
        var data = {}
        data.studentName = this.tableData[i].teacherInfo.studentName
        data.className = this.tableData[i].className
        data.courseName = this.tableData[i].teacherInfo.courseName
        data.score = this.tableData[i].teacherInfo.score
        list.push(data)
      }
      // console.log(list);
      exportExcel(header, list, "教师数据表");
    },
    // 修改页面大小
    handleSizeChange(val) {
      this.q.pageSize = val;
      this.fetchData(this.q.pageIndex, val, this.q.keyword)
    },
    // 修改页
    handleCurrentChange(val) {
      this.q.pageIndex = val;
      console.log(this.q);
      this.fetchData(val, this.q.pageSize, this.q.keyword)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 修改按钮
    updateDialog(data) {
      this.title = '修改'
      console.log(data);
      this.dialogVisible = true
      this.personalInfo = data
      this.addForm.studentId = data.studnetInfo.id
      this.addForm.subjectId = data.courseInfo.id
      this.addForm.score = data.scoreInfo.score
      this.addForm.semesterName = data.termInfo.termName
      this.addForm.classId = data.classInfo.id
    },
    // 删除
    deleteAA(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteScore(id).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.reload()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    // 抓取后台数据
    fetchData(PageIndex, PageSize, keyword) {
      getScore(PageIndex, PageSize, keyword).then((res) => {
        console.log(res);
        if (res.data.code = 200) {
          this.$message.success("获取学生成绩数据成功")
          this.tableData = res.data.data
          // console.log(this.tableData);
          // this.tatal = res.data.page.count
          // this.q.pageIndex = res.data.page.pageIndex
          // this.q.pageSize = res.data.page.pageSize
        } else {
          this.$message.warring('获取学生成绩失败')
        }
      });
    },
    // 搜索
    query() {
      this.fetchData(this.q.pageIndex, this.q.pageSize, this.q.keyword);
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    add() {
      let newObj = {
        date: this.q.date,
        name: this.q.name,
        phoneNo: this.q.phoneNo,
        class: this.q.class,
        address: this.q.address,
        profession: this.q.profession,
      };
      this.list.push(newObj);
    },
  },
};
</script>

<style lang="less" scoped>
.class {
  background: #fff;
  height: 60px;
  line-height: 60px;
  padding-left: 20px;
  margin: 20px 0;
}

.grade-desc {
  background: #fff;
  padding: 20px;
}

.margin {
  margin: 20px 0;
}

.input {
  width: 200px;
}

.button {
  margin-left: 20px;
}

.el-pagination {
  text-align: right;
  margin: 20px 0;
}
</style>